<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑朋友 - 朋友管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f7fa;
            color: #333;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .logo-section {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .logo {
            width: 40px;
            height: 40px;
            filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
        }
        
        .header h1 {
            font-size: 24px;
            font-weight: 500;
        }
        
        .back-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .main-content {
            max-width: 800px;
            margin: 30px auto;
            padding: 0 20px;
        }
        
        .edit-form {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }
        
        .form-title {
            text-align: center;
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-label {
            font-size: 14px;
            font-weight: 500;
            color: #333;
            margin-bottom: 8px;
        }
        
        .form-input {
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-select {
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            background: white;
            transition: border-color 0.3s ease;
        }
        
        .form-select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-textarea {
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            resize: vertical;
            min-height: 100px;
            transition: border-color 0.3s ease;
        }
        
        .form-textarea:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-actions {
            text-align: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 2px solid #f0f0f0;
        }
        
        .btn {
            display: inline-block;
            padding: 12px 30px;
            margin: 0 10px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #95a5a6;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #7f8c8d;
            transform: translateY(-2px);
        }
        
        .loading {
            text-align: center;
            padding: 60px;
            color: #666;
        }
        
        .error {
            text-align: center;
            padding: 60px;
            color: #e74c3c;
        }
        
        .avatar-upload {
            position: relative;
            display: inline-block;
            width: 100px;
            height: 100px;
            border-radius: 50%;
            overflow: hidden;
            border: 2px solid #e1e5e9;
            background-color: #f0f0f0;
            cursor: pointer;
            transition: border-color 0.3s ease;
        }
        
        .avatar-upload:hover {
            border-color: #667eea;
        }
        
        .avatar-preview {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f0f0f0;
        }
        
        .avatar-preview img {
            display: block;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .avatar-input {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }
        
        .avatar-upload-btn {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            background: rgba(0, 0, 0, 0.5);
            color: white;
            text-align: center;
            padding: 5px 0;
            border-radius: 0 0 8px 8px;
            font-size: 12px;
            cursor: pointer;
            transition: background 0.3s ease;
        }
        
        .avatar-upload-btn:hover {
            background: rgba(0, 0, 0, 0.7);
        }
        
        .avatar-info {
            font-size: 12px;
            color: #666;
            margin-top: 8px;
            text-align: center;
        }
        
        .avatar-error {
            color: #e74c3c;
            font-size: 12px;
            margin-top: 5px;
            text-align: center;
        }
        
        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .form-actions {
                display: flex;
                flex-direction: column;
                gap: 10px;
            }
            
            .btn {
                margin: 0;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <div class="logo-section">
                <img src="/static/images/logo-simple.svg" alt="朋友管理系统" class="logo">
                <h1>编辑朋友信息</h1>
            </div>
            <a href="/friend/list" class="back-btn">返回列表</a>
        </div>
    </div>
    
    <div class="main-content">
        <div id="editFormContainer">
            <div class="loading">加载中...</div>
        </div>
    </div>
    
    <script>
        // 获取URL参数中的朋友ID
        function getFriendId() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('id');
        }
        
        // 页面加载完成后获取朋友信息
        document.addEventListener('DOMContentLoaded', function() {
            const friendId = getFriendId();
            if (friendId) {
                loadFriendInfo(friendId);
            } else {
                showError('缺少朋友ID参数');
            }
        });
        
        // 头像上传功能
        let selectedAvatar = null; // 存储选中的头像数据
        
        // 头像文件选择处理函数
        function handleAvatarChange(e) {
            const file = e.target.files[0];
            const avatarError = document.getElementById('avatarError');
            
            // 清除之前的错误信息
            if (avatarError) {
                avatarError.style.display = 'none';
                avatarError.textContent = '';
            }
            
            if (file) {
                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    showAvatarError('请选择图片文件（JPG、PNG、GIF格式）');
                    return;
                }
                
                // 验证文件大小（限制为5MB）
                if (file.size > 5 * 1024 * 1024) {
                    showAvatarError('图片大小不能超过5MB');
                    return;
                }
                
                // 预览图片并转换为Base64
                const reader = new FileReader();
                reader.onload = function(e) {
                    const base64Data = e.target.result;
                    const avatarImage = document.getElementById('avatarImage');
                    if (avatarImage) {
                        avatarImage.src = base64Data;
                    }
                    selectedAvatar = base64Data; // 保存Base64数据
                    
                    // 显示成功提示
                    if (avatarError) {
                        avatarError.style.display = 'block';
                        avatarError.style.color = '#27ae60';
                        avatarError.textContent = '头像选择成功！';
                        // 3秒后隐藏成功提示
                        setTimeout(() => {
                            avatarError.style.display = 'none';
                        }, 3000);
                    }
                };
                
                reader.onerror = function() {
                    showAvatarError('图片读取失败，请重试');
                };
                
                reader.readAsDataURL(file);
            }
        }
        
        // 显示头像错误信息
        function showAvatarError(message) {
            const avatarError = document.getElementById('avatarError');
            if (avatarError) {
                avatarError.style.display = 'block';
                avatarError.style.color = '#e74c3c';
                avatarError.textContent = message;
            }
        }
        
        // 加载朋友信息
        function loadFriendInfo(friendId) {
            fetch(`/friend/api/detail/${friendId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayEditForm(data.data);
                        // 在表单显示后绑定头像选择事件
                        setupAvatarUpload();
                    } else {
                        if (data.message === '请先登录') {
                            window.location.href = '/user/login';
                        } else {
                            showError(data.message);
                        }
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('加载朋友信息失败');
                });
        }
        
        // 设置头像上传功能
        function setupAvatarUpload() {
            const avatarFile = document.getElementById('avatarFile');
            if (avatarFile) {
                avatarFile.addEventListener('change', handleAvatarChange);
            }
        }
        
        // 显示编辑表单
        function displayEditForm(friend) {
            const container = document.getElementById('editFormContainer');
            
            if (!friend) {
                showError('朋友信息不存在');
                return;
            }
            
            container.innerHTML = `
                <form class="edit-form" onsubmit="updateFriend(event)">
                    <div class="form-title">编辑朋友信息</div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">姓名 *</label>
                            <input type="text" class="form-input" id="name" name="name" value="${friend.name || ''}" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">头像</label>
                            <div class="avatar-upload">
                                <div class="avatar-preview" id="avatarPreview">
                                    <img id="avatarImage" src="${friend.avatar || '/static/images/default-avatar.svg'}" alt="头像" onerror="this.src='/static/images/default-avatar.svg'">
                                </div>
                                <input type="file" id="avatarFile" name="avatar" accept="image/*" class="avatar-input">
                                <label for="avatarFile" class="avatar-upload-btn">更换图片</label>
                            </div>
                            <div class="avatar-info">支持 JPG、PNG、GIF 格式，文件大小不超过 5MB</div>
                            <div id="avatarError" class="avatar-error" style="display: none;"></div>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">邮箱</label>
                            <input type="email" class="form-input" id="email" name="email" value="${friend.email || ''}">
                        </div>
                        <div class="form-group">
                            <label class="form-label">电话</label>
                            <input type="tel" class="form-input" id="phone" name="phone" value="${friend.phone || ''}">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">地址</label>
                            <input type="text" class="form-input" id="address" name="address" value="${friend.address || ''}">
                        </div>
                        <div class="form-group">
                            <label class="form-label">生日</label>
                            <input type="date" class="form-input" id="birthday" name="birthday" value="${friend.birthday || ''}">
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">学校</label>
                            <input type="text" class="form-input" id="school" name="school" value="${friend.school || ''}">
                        </div>
                        <div class="form-group">
                            <label class="form-label">备注</label>
                            <textarea class="form-textarea" id="notes" name="notes">${friend.notes || ''}</textarea>
                        </div>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">保存修改</button>
                        <a href="/friend/list" class="btn btn-secondary">取消</a>
                    </div>
                </form>
            `;
        }
        
        // 更新朋友信息
        function updateFriend(event) {
            event.preventDefault();
            
            const friendId = getFriendId();
            if (!friendId) {
                alert('缺少朋友ID参数');
                return;
            }
            
            const formData = {
                id: friendId,
                name: document.getElementById('name').value.trim(),
                email: document.getElementById('email').value.trim(),
                phone: document.getElementById('phone').value.trim(),
                address: document.getElementById('address').value.trim(),
                birthday: document.getElementById('birthday').value,
                school: document.getElementById('school').value.trim(),
                notes: document.getElementById('notes').value.trim(),
                avatar: selectedAvatar || document.getElementById('avatarImage').src // 使用新选择的头像或当前头像
            };
            
            // 验证必填字段
            if (!formData.name) {
                alert('请输入姓名');
                return;
            }
            
            fetch('/friend/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    window.location.href = '/friend/list';
                } else {
                    alert('更新失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新失败，请稍后重试');
            });
        }
        
        // 显示错误信息
        function showError(message) {
            const container = document.getElementById('editFormContainer');
            container.innerHTML = `
                <div class="error">
                    <h3>出错了</h3>
                    <p>${message}</p>
                    <a href="/friend/list" class="btn btn-primary">返回列表</a>
                </div>
            `;
        }
    </script>
</body>
</html>
